package dao

import (
	"context"
	"fmt"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"strconv"
	"strings"
	"time"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/helper/resphelper"
	"yundian/internel/app/models/complaintslog"
	"yundian/internel/app/models/devices"
	"yundian/internel/app/models/dividendslog"
	"yundian/internel/app/models/incomes"
	"yundian/internel/app/models/orders"
	"yundian/internel/app/models/placemodel"
	"yundian/internel/app/models/prices"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
	"yundian/internel/pkg/wechatpay"
)

// -------------------- dao层 - 订单相关操作 -----------------------//

type OrderDao struct {
}

func NewOrderDao() *OrderDao {
	return &OrderDao{}
}

// CountOrderByTradeNoAndOpenid 计算订单条数
func (d *OrderDao) CountOrderByTradeNoAndOpenid(tradeNo string, openid string) *dingo.ErrorWrap {
	var count int64
	sql := "select count(*) from orders where trade_no = ? and openid = ?"
	db := global.Orm.Debug().Raw(sql, tradeNo, openid).Count(&count)
	return dingo.ErrorIf(db.Error, count)
}

func (d *OrderDao) CountOrderByTradeNo(tradeNo string) *dingo.ErrorWrap {
	var count int64
	sql := "select count(*) from orders where trade_no = ?"
	db := global.Orm.Debug().Raw(sql, tradeNo).Count(&count)
	return dingo.ErrorIf(db.Error, count)
}

// 计算订单总数 商户显示的是未被抽单的 (4月2号更新之后的数据)
func (d *OrderDao) CountOrderByPlaceId(placeId int) *dingo.ErrorWrap {
	var count int64
	sql := "select count(id) from orders where place_id = ? and is_draw = 0 and is_tianhai = 0"
	db := global.Orm.Raw(sql, placeId).Count(&count)
	return dingo.ErrorIf(db.Error, count)
}

// 计算代理商订单总数  (4月2号更新之后的数据)
func (d *OrderDao) CountOrderByAgentId(userId int, IsDraw, IsAdmin uint8) *dingo.ErrorWrap { //
	var count int64

	db := global.Orm.Table("orders o").Where("is_tianhai = 0")

	if IsAdmin != helper.TypeNumIsAdminOperator {
		userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		placesIdArr := NewUserDao().GetPlacesIds(userId, userIdArr).Unwrap().([]int)
		db.Where("place_id in ?", placesIdArr)

		if IsDraw != helper.TypeNumIsDrawOpen {
			db.Where("is_draw<>?", 1)
		}
	}

	db.Count(&count)
	//sql := "select count(*) from orders where parent_id = ? and is_tianhai = 0"
	//db := global.Orm.Raw(sql, placeId).Count(&count)
	return dingo.ErrorIf(db.Error, count)
}

// 计算某天前的  已完成交易的交易总额
func (d *OrderDao) CountTradeTotalByAgentId(userId, day int, IsAdmin, IsPlace, IsDraw uint8) *dingo.ErrorWrap {
	var total int64
	db := global.Orm.Debug().Table("orders o").Select(`IFNULL(SUM(settlement_money),0)total`).
		Joins("LEFT JOIN orders_user_relevancy our ON o.trade_no=our.trade_no")
	db.Where("our.user_id=?", userId)
	db.Where("state = ?", helper.TypeNumOrderStatusFinish)
	//db.Where(`our.end_date>=date_sub(curdate(), INTERVAL ? DAY ) and state = ?`, day, helper.TypeNumOrderStatusFinish)

	dateStr := time.Now().AddDate(0, 0, -day).Format("2006-01-02")
	if day <= 1 {
		db.Where("DATE_FORMAT(FROM_UNIXTIME(o.end_at),'%Y-%m-%d') = ?", dateStr)
	} else {
		db.Where("DATE_FORMAT(FROM_UNIXTIME(o.end_at),'%Y-%m-%d') >= ?", dateStr)
	}

	if IsAdmin != helper.TypeNumIsAdminOperator {
		//if IsDraw != helper.TypeNumIsDrawOpen {
		//	db.Where("o.is_draw<>? or o.agent_user_id=?", helper.TypeNumIsDrawOpen, userId)
		//} else {
		//	db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, userId)
		//}
		db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, userId)
		db.Where("o.is_tianhai = 0")
	}

	db.Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// InsertOrder 新增订单
func (d *OrderDao) InsertOrder(m *orders.OrderModel) *dingo.ErrorWrap {
	db := global.Orm.Table("orders").Create(m)
	return dingo.ErrorIf(db.Error, true)
}

// 查询订单扣费类型
func (d *OrderDao) GetOrderPriceTypeList(productIds []string) *dingo.ErrorWrap {
	var lst []*prices.PriceModel
	db := global.Orm.Debug().Table("prices").Where("product_id IN (?)", productIds).Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

func (d *OrderDao) GetOrderWxList(param *request.OrderListReq) *dingo.ErrorWrap {

	var (
		lst    []*request.OrderWxListRes
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)
	fields := `o.id,appid, mchid, openid, trade_no, trade_type, trade_state, trade_state_doing, trade_state_desc, 
	state, title, device_sn, shared_mode, fee_mode, o.user_id, user_name, money, money_str, pay_money, pay_money_str, refund_money, 
	settlement_way, settlement_money, settlement_money_str, settlement_state, coupon_type, coupon_money, coupon_money_str, order_from, 
	pay_from, pay_type, place_id, place_name, member_id, member_name, overtime_state, is_delete, is_draw, pay_at, create_at, update_at, 
	refund_at, end_at, delete_at, draw_at, parent_id, product_id, is_tianhai, agent_user_id, ka_user_id, phone, begin_at`
	db := global.Orm.Debug().Table("orders o").Select(fields)
	db.Where("o.member_id = ?", param.MemberId)
	if param.State > 0 {
		db.Where("o.state = ?", param.State)
	}
	if param.TradeNo != "" {
		db.Where("o.trade_no=?", param.TradeNo)
	}

	db.Order("o.id desc")
	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}

// GetChargeOrderList 获取订单列表API--根据关联表查询出来的订单列表
func (d *OrderDao) GetChargeOrderList(param *request.OrderListReq, ex int) *dingo.ErrorWrap {

	var (
		lst    []*orders.OrderList
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
		fields string
	)

	// 是否导出
	fields = `o.trade_no,o.id,o.appid, o.mchid, o.openid, o.out_trade_no, o.trade_type, o.trade_state,
	o.trade_state_doing, o.trade_state_desc, o.state, o.title, o.device_sn, o.shared_mode, o.fee_mode,
	o.money, o.money_str, o.pay_money, o.pay_money_str, o.refund_money, o.settlement_way, o.settlement_money,
	o.settlement_money_str, o.settlement_state, o.coupon_type, o.coupon_money, o.coupon_money_str,
	o.order_from, o.pay_from, o.pay_type, o.place_id, p.place_name, o.member_id, o.overtime_state,
	o.is_delete, o.is_draw, o.pay_at, o.create_at, o.update_at, o.refund_at, o.end_at, o.parent_id,
	o.product_id, o.agent_user_id, o.begin_at,REPLACE(o.phone, SUBSTR(phone,4,4), '****') as phone,
	REPLACE(o.member_name, SUBSTR(member_name,4,4), '****') as member_name`

	db := global.Orm.Debug().Table("orders o").Select(fields)

	// 查询条件：用户名称
	if param.UserId > 0 {
		// 根据用户名称条件查询该用户下的所有订单
		db.Joins("RIGHT JOIN (SELECT id FROM orders_user_relevancy where user_id = ?) as our ON o.id = our.id", param.UserId)
	} else {
		// 运营商、运营商下的员工、超级管理员  不关联查询、提升查询效率。同时可以查询其他代理用户下的订单
		// 使用当前登录的用户查询当前用户下的所有订单,这样只能查询自己名下的订单
		//if param.LoginUserId != 2 {
		//	db.Joins("RIGHT JOIN (SELECT id FROM orders_user_relevancy where user_id = ?) as our ON o.id = our.id", param.LoginUserId)
		//}
		db.Joins("RIGHT JOIN (SELECT id FROM orders_user_relevancy where user_id = ?) as our ON o.id = our.id", param.LoginUserId)
	}
	db.Joins("LEFT JOIN places p ON o.place_id = p.id")
	db.Where("o.user_id > 0")

	// 查询条件：订单号
	if param.TradeNo != "" {
		db.Where("o.trade_no=?", param.TradeNo)
	}
	if param.OutTradeNo != "" {
		db.Where("o.out_trade_no=?", param.OutTradeNo)
	} // 查询条件：第三方订单号
	if param.DeviceSn != "" {
		db.Where("o.device_sn=?", param.DeviceSn)
	} // 查询条件：设备序列号
	if param.PlaceId > 0 {
		db.Where("o.place_id = ?", param.PlaceId)
	} // 查询条件：门店ID
	if param.State > 0 { // 查询条件：订单状态
		db.Where("o.state = ?", param.State)
	} else {
		db.Where("o.state != 1")
	}
	if param.OrderFrom != "" {
		db.Where("o.order_from = ?", param.OrderFrom)
	} // 查询条件：支付方式
	if param.Phone != "" {
		db.Where("o.phone=?", param.Phone)
	} // 查询条件：手机号码
	if param.Openid != "" {
		db.Where("o.openid = ?", param.Openid)
	} // 查询条件：openid

	// 根据用户查询
	//if param.UserId > 0 {
	//	db.Where("our.user_id = ?", param.UserId) // 查询的用户下的订单
	//} else {
	//	db.Where("our.user_id = ?", param.LoginUserId) // 默认显示当前登录用户下的订单
	//}

	// 抽单判断
	if param.IsDraw == 1 && param.IsTianhai == 0 {
		if param.UserId > 0 {
			db.Where("o.is_tianhai != 8 AND (o.is_draw=1 AND o.agent_user_id = ?) OR o.is_draw=0", param.UserId) // 查询的用户下的抽单
		} else {
			db.Where("o.is_tianhai != 8 AND (o.is_draw=1 AND o.agent_user_id = ?) OR o.is_draw=0", param.LoginUserId) // 默认显示当前登录的用户的抽单
		}
	} else if param.IsDraw == 1 && param.IsTianhai == 8 {
		db.Where("o.is_tianhai = 8")
	} else { // 没有抽单
		db.Where("o.is_draw = 0")
	}

	// 时间查询
	if param.BeginTime != "" {
		beginTime := strings.Split(param.BeginTime, ",")
		b, _ := strconv.Atoi(beginTime[0])
		e, _ := strconv.Atoi(beginTime[1])
		sTime, eTime := wechatpay.TimeConvStartEnd(int64(b), int64(e))
		db.Where("o.create_at >= ? and o.create_at <= ?", sTime, eTime)
		//db.Where("DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') >=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') and "+
		//	"DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d')<=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", beginTime[0], beginTime[1])
	}
	if param.EndTime != "" {
		endTime := strings.Split(param.EndTime, ",")
		b, _ := strconv.Atoi(endTime[0])
		e, _ := strconv.Atoi(endTime[1])
		sTime, eTime := wechatpay.TimeConvStartEnd(int64(b), int64(e))
		db.Where("o.end_at >= ? and o.end_at <= ?", sTime, eTime)
		//db.Where("DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') >=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') and "+
		//	"DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d')<=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime[0], endTime[1])
	}

	// 过滤
	if len(param.PayFromFilter) > 0 {
		db.Where("o.pay_from in ?", param.PayFromFilter)
	}
	if len(param.OrderFromFilter) > 0 {
		db.Where("o.order_from in ?", param.OrderFromFilter)
	}
	if len(param.StatusFilter) > 0 {
		db.Where("o.state in ?", param.StatusFilter)
	}

	// 排序
	if param.SortField != "" && param.SortOrder == "ascend" {
		db.Order(fmt.Sprintf("o.%s asc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField != "" && param.SortOrder == "descend" {
		db.Order(fmt.Sprintf("o.%s desc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField == "" {
		db.Order("o.id desc")
	}

	db.Limit(limit).Offset(offset).Find(&lst)
	if param.CountStatus != helper.TypeNumCountStatusNo {
		db.Limit(-1).Offset(-1).Count(&count)
	}

	return dingo.ErrorIf(db.Error, lst, count)
}

// GetOrderList 获取订单列表API--根据关联表查询出来的订单列表
func (d *OrderDao) GetOrderList(param *request.OrderListReq, ex int) *dingo.ErrorWrap {

	var (
		lst    []*orders.OrderList
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
		fields string
	)

	fields = `o.trade_no,o.id,o.appid, o.mchid, o.openid, o.out_trade_no, o.trade_type, o.trade_state,
o.trade_state_doing, o.trade_state_desc, o.state, o.title, o.device_sn, o.shared_mode, o.fee_mode,
o.money, o.money_str, o.pay_money, o.pay_money_str, o.refund_money, o.settlement_way, o.settlement_money,
o.settlement_money_str, o.settlement_state, o.coupon_type, o.coupon_money, o.coupon_money_str,
o.order_from, o.pay_from, o.pay_type, o.place_id, o.place_name, o.member_id, o.overtime_state,
o.is_delete, o.is_draw, o.pay_at, o.create_at, o.update_at, o.refund_at, o.end_at, o.parent_id,
o.product_id, o.agent_user_id, o.begin_at,REPLACE(o.phone, SUBSTR(phone,4,4), '****') as phone,
REPLACE(o.member_name, SUBSTR(member_name,4,4), '****') as member_name`
	if ex == 1 {
		fields = `o.trade_no,o.id,o.appid, o.mchid, o.openid, o.out_trade_no, o.trade_type, o.trade_state,
o.trade_state_doing, o.trade_state_desc, o.state, o.title, o.device_sn, o.shared_mode, o.fee_mode,
o.money, o.money_str, o.pay_money, o.pay_money_str, o.refund_money, o.settlement_way, o.settlement_money,
o.settlement_money_str, o.settlement_state, o.coupon_type, o.coupon_money, o.coupon_money_str,
o.order_from, o.pay_from, o.pay_type, o.place_id, p.place_name, p.hotel_id, o.member_id, o.overtime_state,
o.is_delete, o.is_draw, o.pay_at, o.create_at, o.update_at, o.refund_at, o.end_at, o.parent_id,
o.product_id, o.agent_user_id, o.begin_at,REPLACE(o.phone, SUBSTR(phone,4,4), '****') as phone,
REPLACE(o.member_name, SUBSTR(member_name,4,4), '****') as member_name`
	}

	db := global.Orm.Debug().Table("orders o").Select(fields)
	if ex == 1 {
		db.Joins("LEFT JOIN places p ON o.place_id = p.id")
	}

	// 查询条件：用户名称
	if param.UserId > 0 {
		// 根据用户名称条件查询该用户下的所有订单
		db.Joins("RIGHT JOIN (SELECT id FROM orders_user_relevancy where user_id = ?) as our ON o.id = our.id", param.UserId)
	} else {
		// 运营商、运营商下的员工、超级管理员  不关联查询、提升查询效率。同时可以查询其他代理用户下的订单
		// 使用当前登录的用户查询当前用户下的所有订单,这样只能查询自己名下的订单
		//if param.LoginUserId != 2 {
		//	db.Joins("RIGHT JOIN (SELECT id FROM orders_user_relevancy where user_id = ?) as our ON o.id = our.id", param.LoginUserId)
		//}
		db.Joins("RIGHT JOIN (SELECT id FROM orders_user_relevancy where user_id = ?) as our ON o.id = our.id", param.LoginUserId)
	}
	db.Where("o.user_id > 0")

	// 查询条件：订单号
	if param.TradeNo != "" {
		db.Where("o.trade_no=?", param.TradeNo)
	}
	if param.OutTradeNo != "" {
		db.Where("o.out_trade_no=?", param.OutTradeNo)
	} // 查询条件：第三方订单号
	if param.DeviceSn != "" {
		db.Where("o.device_sn=?", param.DeviceSn)
	} // 查询条件：设备序列号
	if param.PlaceId > 0 {
		db.Where("o.place_id = ?", param.PlaceId)
	} // 查询条件：门店ID
	if param.State > 0 { // 查询条件：订单状态
		db.Where("o.state = ?", param.State)
	} else {
		db.Where("o.state != 1")
	}
	if param.OrderFrom != "" {
		db.Where("o.order_from = ?", param.OrderFrom)
	} // 查询条件：支付方式
	if param.Phone != "" {
		db.Where("o.phone=?", param.Phone)
	} // 查询条件：手机号码
	if param.Openid != "" {
		db.Where("o.openid = ?", param.Openid)
	} // 查询条件：openid

	if param.ProdType > 0 {
		db.Where("o.prod_type = ?", param.ProdType)
	}

	// 根据用户查询
	//if param.UserId > 0 {
	//	db.Where("our.user_id = ?", param.UserId) // 查询的用户下的订单
	//} else {
	//	db.Where("our.user_id = ?", param.LoginUserId) // 默认显示当前登录用户下的订单
	//}

	// 抽单判断
	if param.IsDraw == 1 && param.IsTianhai == 0 {
		if param.UserId > 0 {
			db.Where("o.is_draw = 1 and o.is_tianhai = 0 and o.agent_user_id = ?", param.UserId) // 查询的用户下的抽单
		} else {
			db.Where("o.is_draw = 1 and o.is_tianhai = 0 and o.agent_user_id = ?", param.LoginUserId) // 默认显示当前登录的用户的抽单
		}
	} else if param.IsDraw == 1 && param.IsTianhai == 8 {
		db.Where("o.is_draw = 1 and o.is_tianhai = 8")
	} else { // 没有抽单
		db.Where("o.is_draw = 0")
	}

	// 时间查询
	if param.BeginTime != "" {
		beginTime := strings.Split(param.BeginTime, ",")
		b, _ := strconv.Atoi(beginTime[0])
		e, _ := strconv.Atoi(beginTime[1])
		sTime, eTime := wechatpay.TimeConvStartEnd(int64(b), int64(e))
		db.Where("o.create_at >= ? and o.create_at <= ?", sTime, eTime)
		//db.Where("DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') >=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') and "+
		//	"DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d')<=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", beginTime[0], beginTime[1])
	}
	if param.EndTime != "" {
		endTime := strings.Split(param.EndTime, ",")
		b, _ := strconv.Atoi(endTime[0])
		e, _ := strconv.Atoi(endTime[1])
		sTime, eTime := wechatpay.TimeConvStartEnd(int64(b), int64(e))
		db.Where("o.end_at >= ? and o.end_at <= ?", sTime, eTime)
		//db.Where("DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') >=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') and "+
		//	"DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d')<=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime[0], endTime[1])
	}

	// 过滤
	if len(param.PayFromFilter) > 0 {
		db.Where("o.pay_from in ?", param.PayFromFilter)
	}
	if len(param.OrderFromFilter) > 0 {
		db.Where("o.order_from in ?", param.OrderFromFilter)
	}
	if len(param.StatusFilter) > 0 {
		db.Where("o.state in ?", param.StatusFilter)
	}

	// 排序
	if param.SortField != "" && param.SortOrder == "ascend" {
		db.Order(fmt.Sprintf("o.%s asc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField != "" && param.SortOrder == "descend" {
		db.Order(fmt.Sprintf("o.%s desc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField == "" {
		db.Order("o.id desc")
	}

	db.Limit(limit).Offset(offset).Find(&lst)
	if param.CountStatus != helper.TypeNumCountStatusNo {
		db.Limit(-1).Offset(-1).Count(&count)
	}

	return dingo.ErrorIf(db.Error, lst, count)
}

// 运维专用
func (d *OrderDao) GetALLOrderListToKf(param *request.OrderListReq) *dingo.ErrorWrap {

	var (
		lst    []*orders.OrderList
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
		fields string
	)

	// 是否导出
	fields = `o.trade_no,o.id,o.appid, o.mchid, o.openid, o.out_trade_no, o.trade_type, o.trade_state,
o.trade_state_doing, o.trade_state_desc, o.state, o.title, o.device_sn, o.shared_mode, o.fee_mode,
o.money, o.money_str, o.pay_money, o.pay_money_str, o.refund_money, o.settlement_way, o.settlement_money,
o.settlement_money_str, o.settlement_state, o.coupon_type, o.coupon_money, o.coupon_money_str,
o.order_from, o.pay_from, o.pay_type, o.place_id, o.place_name, o.member_id, o.overtime_state,
o.is_delete, o.is_draw, o.pay_at, o.create_at, o.update_at, o.refund_at, o.end_at, o.parent_id,
o.product_id, o.agent_user_id, o.begin_at,REPLACE(o.phone, SUBSTR(phone,4,4), '****') as phone,
REPLACE(o.member_name, SUBSTR(member_name,4,4), '****') as member_name`

	db := global.Orm.Debug().Table("orders o").Select(fields).Where("o.user_id > 0")

	// 查询条件：用户名称
	if param.UserId > 0 {
		// 根据用户名称条件查询该用户下的所有订单
		db.Joins("RIGHT JOIN (SELECT id FROM orders_user_relevancy where user_id = ?) as our ON o.id = our.id", param.UserId)
	} else {
		// 运营商、运营商下的员工、超级管理员  不关联查询、提升查询效率。同时可以查询其他代理用户下的订单
		// 使用当前登录的用户查询当前用户下的所有订单,这样只能查询自己名下的订单
		//if param.LoginUserId != 2 {
		//	db.Joins("RIGHT JOIN (SELECT id FROM orders_user_relevancy where user_id = ?) as our ON o.id = our.id", param.LoginUserId)
		//}
		db.Joins("RIGHT JOIN (SELECT id FROM orders_user_relevancy where user_id = ?) as our ON o.id = our.id", param.LoginUserId)
	}

	if param.TradeNo != "" {
		db.Where("o.trade_no=?", param.TradeNo)
	} // 查询条件：订单号
	if param.OutTradeNo != "" {
		db.Where("o.out_trade_no=?", param.OutTradeNo)
	} // 查询条件：第三方订单号
	if param.DeviceSn != "" {
		db.Where("o.device_sn=?", param.DeviceSn)
	} // 查询条件：设备序列号
	if param.PlaceId > 0 {
		db.Where("o.place_id = ?", param.PlaceId)
	} // 查询条件：门店ID
	if param.State > 0 {
		db.Where("o.state = ?", param.State)
	} // 查询条件：订单状态
	if param.OrderFrom != "" {
		db.Where("o.order_from = ?", param.OrderFrom)
	} // 查询条件：支付方式
	if param.Phone != "" {
		db.Where("o.phone=?", param.Phone)
	} // 查询条件：手机号码
	if param.Openid != "" {
		db.Where("o.openid = ?", param.Openid)
	} // 查询条件：openid

	// 根据用户查询
	//if param.UserId > 0 {
	//	db.Where("our.user_id = ?", param.UserId) // 查询的用户下的订单
	//} else {
	//	db.Where("our.user_id = ?", param.LoginUserId) // 默认显示当前登录用户下的订单
	//}

	// 抽单判断
	//if param.IsDraw == 1 && param.IsTianhai == 0 {
	//	if param.UserId > 0 {
	//		db.Where("o.is_draw = 1 and o.is_tianhai = 0 and o.agent_user_id = ?", param.UserId) // 查询的用户下的抽单
	//	} else {
	//		db.Where("o.is_draw = 1 and o.is_tianhai = 0 and o.agent_user_id = ?", param.LoginUserId) // 默认显示当前登录的用户的抽单
	//	}
	//} else if param.IsDraw == 1 && param.IsTianhai == 8 {
	//	db.Where("o.is_draw = 1 and o.is_tianhai = 8")
	//} else { // 没有抽单
	//	db.Where("o.is_draw = 0")
	//}
	db.Where("o.is_tianhai = 8")

	// 时间查询
	if param.BeginTime != "" {
		beginTime := strings.Split(param.BeginTime, ",")
		b, _ := strconv.Atoi(beginTime[0])
		e, _ := strconv.Atoi(beginTime[1])
		sTime, eTime := wechatpay.TimeConvStartEnd(int64(b), int64(e))
		db.Where("o.create_at >= ? and o.create_at <= ?", sTime, eTime)
		//db.Where("DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') >=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') and "+
		//	"DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d')<=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", beginTime[0], beginTime[1])
	}
	if param.EndTime != "" {
		endTime := strings.Split(param.EndTime, ",")
		b, _ := strconv.Atoi(endTime[0])
		e, _ := strconv.Atoi(endTime[1])
		sTime, eTime := wechatpay.TimeConvStartEnd(int64(b), int64(e))
		db.Where("o.end_at >= ? and o.end_at <= ?", sTime, eTime)
		//db.Where("DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') >=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') and "+
		//	"DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d')<=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime[0], endTime[1])
	}

	// 过滤
	if len(param.PayFromFilter) > 0 {
		db.Where("o.pay_from in ?", param.PayFromFilter)
	}
	if len(param.OrderFromFilter) > 0 {
		db.Where("o.order_from in ?", param.OrderFromFilter)
	}
	if len(param.StatusFilter) > 0 {
		db.Where("o.state in ?", param.StatusFilter)
	}

	// 排序
	if param.SortField != "" && param.SortOrder == "ascend" {
		db.Order(fmt.Sprintf("o.%s asc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField != "" && param.SortOrder == "descend" {
		db.Order(fmt.Sprintf("o.%s desc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField == "" {
		db.Order("o.id desc")
	}

	db.Limit(limit).Offset(offset).Find(&lst)
	if param.CountStatus != helper.TypeNumCountStatusNo {
		db.Limit(-1).Offset(-1).Count(&count)
	}

	return dingo.ErrorIf(db.Error, lst, count)
}

// GetOrderListKf 获取订单列表API(客服)
// 客服需要所有订单列表，需要对订单操作
func (d *OrderDao) GetOrderListKf(param *request.OrderListReq) *dingo.ErrorWrap {

	var (
		lst    []*orders.OrderList
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	fields := `o.trade_no,o.id,o.appid, o.mchid, o.openid, o.out_trade_no, o.trade_type, o.trade_state,
o.trade_state_doing, o.trade_state_desc, o.state, o.title, o.device_sn, o.shared_mode, o.fee_mode,
o.money, o.money_str, o.pay_money, o.pay_money_str, o.refund_money, o.settlement_way, o.settlement_money,
o.settlement_money_str, o.settlement_state, o.coupon_type, o.coupon_money, o.coupon_money_str,
o.order_from, o.pay_from, o.pay_type, o.place_id, o.place_name, o.member_id, o.overtime_state,
o.is_delete, o.is_draw, o.pay_at, o.create_at, o.update_at, o.refund_at, o.end_at, o.parent_id,
o.product_id, o.agent_user_id, o.begin_at,REPLACE(o.phone, SUBSTR(phone,4,4), '****') as phone,
REPLACE(o.member_name, SUBSTR(member_name,4,4), '****') as member_name`

	db := global.Orm.Debug().Table("orders o").Select(fields)
	//db.Joins("LEFT JOIN places p ON o.place_id = p.id")

	if param.DeviceSn != "" { db.Where("o.device_sn like ?", fmt.Sprint("%", param.DeviceSn, "%")) } // 查询条件：设备序列号

	if param.TradeNo != "" {
		db.Where("o.trade_no=?", param.TradeNo)
	} // 查询条件：订单号
	if param.OutTradeNo != "" {
		db.Where("o.out_trade_no=?", param.OutTradeNo)
	} // 查询条件：第三方订单号

	if param.UserId > 0 {
		db.Where("o.user_id = ?", param.UserId)
	} // 查询条件：用户ID
	if param.PlaceId > 0 {
		db.Where("o.place_id = ?", param.PlaceId)
	} // 查询条件：门店ID
	if param.State > 0 {
		db.Where("o.state = ?", param.State)
	} // 查询条件：订单状态
	if param.OrderFrom != "" {
		db.Where("o.order_from = ?", param.OrderFrom)
	} // 查询条件：支付方式
	if param.Phone != "" {
		db.Where("o.phone=?", param.Phone)
	} // 查询条件：手机号码
	if param.Openid != "" {
		db.Where("o.openid = ?", param.Openid)
	} // 查询条件：openid
	if param.IsTianhai > 0 && param.IsTianhai == 1 {
		db.Where("o.is_draw = 1")
	} // 所有
	if param.IsTianhai > 0 && param.IsTianhai == 2 {
		db.Where("o.is_draw = 1 and o.is_tianhai = 0")
	}
	if param.IsTianhai > 0 && param.IsTianhai == 8 {
		db.Where("o.is_draw = 1 and o.is_tianhai = 8")
	}
	if param.ProdType > 0 {
		db.Where("o.prod_type = ?", param.ProdType)
	}

	// 时间查询
	if param.BeginTime != "" {
		beginTime := strings.Split(param.BeginTime, ",")
		b, _ := strconv.Atoi(beginTime[0])
		e, _ := strconv.Atoi(beginTime[1])
		sTime, eTime := wechatpay.TimeConvStartEnd(int64(b), int64(e))
		db.Where("o.create_at >= ? and o.create_at <= ?", sTime, eTime)
		//db.Where("DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') >=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') and "+
		//	"DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d')<=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", beginTime[0], beginTime[1])
	}
	if param.EndTime != "" {
		endTime := strings.Split(param.EndTime, ",")
		b, _ := strconv.Atoi(endTime[0])
		e, _ := strconv.Atoi(endTime[1])
		sTime, eTime := wechatpay.TimeConvStartEnd(int64(b), int64(e))
		db.Where("o.end_at >= ? and o.end_at <= ?", sTime, eTime)
		//db.Where("DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') >=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') and "+
		//	"DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d')<=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime[0], endTime[1])
	}

	// 过滤
	if len(param.PayFromFilter) > 0 {
		db.Where("o.pay_from in ?", param.PayFromFilter)
	}
	if len(param.OrderFromFilter) > 0 {
		db.Where("o.order_from in ?", param.OrderFromFilter)
	}
	if len(param.StatusFilter) > 0 {
		db.Where("o.state in ?", param.StatusFilter)
	}

	// 排序
	if param.SortField != "" && param.SortOrder == "ascend" {
		db.Order(fmt.Sprintf("o.%s asc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField != "" && param.SortOrder == "descend" {
		db.Order(fmt.Sprintf("o.%s desc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField == "" {
		db.Order("o.id desc")
	}

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)
	return dingo.ErrorIf(db.Error, lst, count)
}

func (d *OrderDao) ExportOrderListKf(param *request.OrderListReq) *dingo.ErrorWrap {

	var (
		lst    []*orders.OrderList
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	fields := `o.trade_no,o.id,o.appid, o.mchid, o.openid, o.out_trade_no, o.trade_type, o.trade_state,
o.trade_state_doing, o.trade_state_desc, o.state, o.title, o.device_sn, o.shared_mode, o.fee_mode,
o.money, o.money_str, o.pay_money, o.pay_money_str, o.refund_money, o.settlement_way, o.settlement_money,
o.settlement_money_str, o.settlement_state, o.coupon_type, o.coupon_money, o.coupon_money_str,
o.order_from, o.pay_from, o.pay_type, o.place_id, p.place_name, o.member_id, o.overtime_state,
o.is_delete, o.is_draw, o.pay_at, o.create_at, o.update_at, o.refund_at, o.end_at, o.parent_id,
o.product_id, o.agent_user_id, o.begin_at,REPLACE(o.phone, SUBSTR(phone,4,4), '****') as phone,
REPLACE(o.member_name, SUBSTR(member_name,4,4), '****') as member_name`

	db := global.Orm.Debug().Table("orders o").Select(fields)
	db.Joins("LEFT JOIN places p ON o.place_id = p.id")

	if param.DeviceSn != "" { db.Where("o.device_sn like ?", fmt.Sprint("%", param.DeviceSn, "%")) } // 查询条件：设备序列号

	if param.TradeNo != "" {
		db.Where("o.trade_no=?", param.TradeNo)
	} // 查询条件：订单号
	if param.OutTradeNo != "" {
		db.Where("o.out_trade_no=?", param.OutTradeNo)
	} // 查询条件：第三方订单号

	if param.UserId > 0 {
		db.Where("o.user_id = ?", param.UserId)
	} // 查询条件：用户ID
	if param.PlaceId > 0 {
		db.Where("o.place_id = ?", param.PlaceId)
	} // 查询条件：门店ID
	if param.State > 0 {
		db.Where("o.state = ?", param.State)
	} // 查询条件：订单状态
	if param.OrderFrom != "" {
		db.Where("o.order_from = ?", param.OrderFrom)
	} // 查询条件：支付方式
	if param.Phone != "" {
		db.Where("o.phone=?", param.Phone)
	} // 查询条件：手机号码
	if param.Openid != "" {
		db.Where("o.openid = ?", param.Openid)
	} // 查询条件：openid
	if param.IsTianhai > 0 && param.IsTianhai == 1 {
		db.Where("o.is_draw = 1")
	} // 所有
	if param.IsTianhai > 0 && param.IsTianhai == 2 {
		db.Where("o.is_draw = 1 and o.is_tianhai = 0")
	}
	if param.IsTianhai > 0 && param.IsTianhai == 8 {
		db.Where("o.is_draw = 1 and o.is_tianhai = 8")
	}
	if param.ProdType > 0 {
		db.Where("o.prod_type = ?", param.ProdType)
	}

	// 时间查询
	if param.BeginTime != "" {
		beginTime := strings.Split(param.BeginTime, ",")
		b, _ := strconv.Atoi(beginTime[0])
		e, _ := strconv.Atoi(beginTime[1])
		sTime, eTime := wechatpay.TimeConvStartEnd(int64(b), int64(e))
		db.Where("o.create_at >= ? and o.create_at <= ?", sTime, eTime)
		//db.Where("DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') >=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') and "+
		//	"DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d')<=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", beginTime[0], beginTime[1])
	}
	if param.EndTime != "" {
		endTime := strings.Split(param.EndTime, ",")
		b, _ := strconv.Atoi(endTime[0])
		e, _ := strconv.Atoi(endTime[1])
		sTime, eTime := wechatpay.TimeConvStartEnd(int64(b), int64(e))
		db.Where("o.end_at >= ? and o.end_at <= ?", sTime, eTime)
		//db.Where("DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') >=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') and "+
		//	"DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d')<=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime[0], endTime[1])
	}

	// 过滤
	if len(param.PayFromFilter) > 0 {
		db.Where("o.pay_from in ?", param.PayFromFilter)
	}
	if len(param.OrderFromFilter) > 0 {
		db.Where("o.order_from in ?", param.OrderFromFilter)
	}
	if len(param.StatusFilter) > 0 {
		db.Where("o.state in ?", param.StatusFilter)
	}

	// 排序
	if param.SortField != "" && param.SortOrder == "ascend" {
		db.Order(fmt.Sprintf("o.%s asc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField != "" && param.SortOrder == "descend" {
		db.Order(fmt.Sprintf("o.%s desc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField == "" {
		db.Order("o.id desc")
	}

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)
	return dingo.ErrorIf(db.Error, lst, count)
}

// GetOrderListYw 获取订单列表API(运营) 关闭
//func (d *OrderDao) GetOrderListYw(param *request.OrderListReq) *dingo.ErrorWrap {
//
//	var (
//		lst    []*orders.OrderModel
//		count  int64
//		limit  int = param.PageSize
//		offset int = param.PageSize * (param.PageNo - 1)
//	)
//	//db := global.Orm.Debug().Table("orders").Where("is_tianhai != ?", 8)
//	db := global.Orm.Debug().Table("orders")
//
//	if param.TradeNo != "" {
//		db.Where("trade_no=?", param.TradeNo)
//	} // 查询条件：订单号
//	if param.OutTradeNo != "" {
//		db.Where("out_trade_no=?", param.OutTradeNo)
//	} // 查询条件：第三方订单号
//	if param.DeviceSn != "" {
//		db.Where("device_sn=?", param.DeviceSn)
//	} // 查询条件：设备序列号
//	if param.UserId > 0 {
//		db.Where("user_id = ?", param.UserId)
//	} // 查询条件：用户ID
//	if param.PlaceId > 0 {
//		db.Where("place_id = ?", param.PlaceId)
//	} // 查询条件：门店ID
//	if param.State > 0 {
//		db.Where("state = ?", param.State)
//	} // 查询条件：订单状态
//	if param.OrderFrom != "" {
//		db.Where("order_from = ?", param.OrderFrom)
//	} // 查询条件：支付方式
//	if param.Phone != "" {
//		db.Where("phone=?", param.Phone)
//	} // 查询条件：手机号码
//	if param.Openid != "" {
//		db.Where("openid = ?", param.Openid)
//	} // 查询条件：openid
//
//	// 时间查询
//	if param.BeginTime != "" {
//		beginTime := strings.Split(param.BeginTime, ",")
//		db.Where("DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') >=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') and "+
//			"DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d')<=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", beginTime[0], beginTime[1])
//	}
//	if param.EndTime != "" {
//		endTime := strings.Split(param.EndTime, ",")
//		db.Where("DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') >=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') and "+
//			"DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d')<=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime[0], endTime[1])
//		//db.Where("end_date >=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') and "+
//		//	"end_date <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime[0], endTime[1])
//	}
//
//	// 过滤
//	if len(param.PayFromFilter) > 0 {
//		db.Where("pay_from in ?", param.PayFromFilter)
//	}
//	if len(param.OrderFromFilter) > 0 {
//		db.Where("order_from in ?", param.OrderFromFilter)
//	}
//	if len(param.StatusFilter) > 0 {
//		db.Where("state in ?", param.StatusFilter)
//	}
//
//	// 排序
//	if param.SortField != "" && param.SortOrder == "ascend" {
//		db.Order(fmt.Sprintf("%s asc", utils.String(param.SortField).SnakeCase()))
//	}
//	if param.SortField != "" && param.SortOrder == "descend" {
//		db.Order(fmt.Sprintf("%s desc", utils.String(param.SortField).SnakeCase()))
//	}
//	if param.SortField == "" {
//		db.Order("trade_no desc")
//	}
//
//	db.Limit(limit).Offset(offset).Find(&lst)
//	if param.CountStatus != helper.TypeNumCountStatusNo {
//		db.Limit(-1).Offset(-1).Count(&count)
//	}
//
//	return dingo.ErrorIf(db.Error, lst, count)
//}

func (d *OrderDao) GetOrderListByOpenid(param *request.OrderListReq) *dingo.ErrorWrap {

	var (
		lst    []*orders.OrderModel
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.Debug().Table("orders").Where("openid = ?", param.Openid)

	// 排序
	if param.SortField != "" && param.SortOrder == "ascend" {
		db.Order(fmt.Sprintf("%s asc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField != "" && param.SortOrder == "descend" {
		db.Order(fmt.Sprintf("%s desc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField == "" {
		db.Order("create_at desc")
	}

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}

// 订单列表-无奖励单
func (d *OrderDao) GetNoRewardOrderList(param *request.OrderListReq) *dingo.ErrorWrap {
	var (
		lst    []*orders.OrderModel
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)
	db := global.Orm.Debug().Table("orders")
	db.Where("is_draw <> ?", 1) // 不显示奖励单

	userInfo := NewUserDao().GetUserInfoById(param.ParentId).Unwrap().(*users.UserModel)
	// 当前员工不属于运营商
	if param.IsAdmin == 4 && userInfo.IsAdmin != 2 {
		// 当前账号登录维护员工，可以查询该员工所在运营商或是代理商的所有订单，方便管理
		placeModelLst := NewPlaceDao().GetPlaceByparentId(param.ParentId).Unwrap().([]*placemodel.PlaceModel)
		// 获取维护者所维护的商户ID
		//placeModelLst := NewPlaceDao().GetPlaceListByMaintainerId(param.LoginUserId).Unwrap().([]*placemodel.PlaceModel)
		placeIdArr := make([]int, 0)
		//log.Println("placeModelLst 数组长度：", len(placeModelLst))
		for _, placeModel := range placeModelLst {
			//fmt.Println("placeId: ",placeModel.Id)
			placeIdArr = append(placeIdArr, placeModel.Id)
		}
		//log.Println("placeIdArr dao数组：", placeIdArr)
		db.Where("place_id in ?", placeIdArr)
	}

	if param.IsAdmin == helper.TypeNumIsAdminAgent || param.IsAdmin == helper.TypeNumIsAdminPartner { //当前账号登录是代理商或是合伙人
		//// 获取某个用户下的所有代理商用户ID
		//placeModelLst := NewPlaceDao().GetPlaceByparentId(param.LoginUserId).Unwrap().([]*placemodel.PlaceModel)
		//placeIdArr := make([]int, 0)
		////log.Println("placeModelLst 数组长度：", len(placeModelLst))
		//for _, placeModel := range placeModelLst {
		//	//fmt.Println("placeId: ",placeModel.Id)
		//	placeIdArr = append(placeIdArr, placeModel.Id)
		//}
		////log.Println("placeIdArr dao数组：", placeIdArr)
		//db.Where("place_id in ?", placeIdArr)

		// 查询代理商所有下级
		userIdArr := NewUserDao().QueryChildUserIds(param.LoginUserId).Unwrap().([]int)
		userIdArr = append(userIdArr, param.LoginUserId)
		placeModelLst := NewPlaceDao().GetPlaceByParentIds(userIdArr).Unwrap().([]*placemodel.PlaceModel)
		placeIdArr := make([]int, 0)
		for _, placeModel := range placeModelLst {
			placeIdArr = append(placeIdArr, placeModel.Id)
		}
		db.Where("place_id in ?", placeIdArr)
	}

	if param.TradeNo != "" { //网点名称
		db.Where("trade_no like ?", fmt.Sprint("%", param.TradeNo, "%"))
	}
	if param.OutTradeNo != "" {
		db.Where("out_trade_no like ?", fmt.Sprint("%", param.OutTradeNo, "%"))
	}
	if param.PlaceId > 0 {
		db.Where("is_draw = ?", 0)
		db.Where("place_id = ?", param.PlaceId)
	}

	if param.Phone != "" {
		db.Where("phone like ?", fmt.Sprint("%", param.Phone, "%"))
	}
	if param.PlaceName != "" { // 查询条件：网点名称
		db.Where("place_name like ? ", fmt.Sprint("%", param.PlaceName, "%"))
	}
	if param.DeviceSn != "" { // 查询条件：设备序列号
		db.Where("device_sn like ?", fmt.Sprint("%", param.DeviceSn, "%"))
	}
	if param.State > 0 { // 查询条件：状态
		db.Where("state = ?", param.State)
	}
	if param.SettlementState > 0 { // 查询条件：异常状态
		db.Where("settlement_state = ?", param.SettlementState)
	}
	if param.OrderFrom != "" { // 查询条件：支付方式
		db.Where("order_from = ?", param.OrderFrom)
	}
	if param.PayFrom != "" { // 查询条件：支付方式
		db.Where("pay_from = ?", param.PayFrom)
	}
	if param.SharedMode != "" { // 查询条件：共享模式
		db.Where("shared_mode = ?", param.SharedMode)
	}
	if param.TradeType != "" { // 查询条件：收费模式
		db.Where("trade_type = ?", param.TradeType)
	}
	if param.UserId > 0 { // 选择代理商用户ID
		if param.IsNext > 0 { // 是否查询下级
			// 获取该用户下的所有代理商的用户ID
			//pidArr := []int{param.UserId}
			//userIdArr := NewUserDao().GetUserIdByPid(param.UserId).Unwrap().([]int)
			//if len(userIdArr) > 0 {
			//	 NewUserDao().GetUserIdByPid(userIdArr).Unwrap().([]int)
			//}
			//
			//append(userIdArr, )
			// 获取该代理商下的所有网点ID
			//db.Where("user_id in (?)", userIdArr)
		} else {
			// 获取该代理商下的所有网点ID
			db.Where("user_id = ?", param.UserId)

		}
	}

	if param.MemberId != "" {
		db.Where("member_id = ?", param.MemberId)
	}

	// 时间查询
	if param.BeginTime != "" {
		beginTime := strings.Split(param.BeginTime, ",")
		db.Where("create_at >= ? and create_at<= ?", beginTime[0], beginTime[1])
	}
	if param.EndTime != "" {
		endTime := strings.Split(param.EndTime, ",")
		db.Where("end_at >= ? and end_at<= ?", endTime[0], endTime[1])
	}

	// 过滤
	if len(param.PayFromFilter) > 0 {
		db.Where("pay_from in ?", param.PayFromFilter)
	}
	if len(param.OrderFromFilter) > 0 {
		db.Where("order_from in ?", param.OrderFromFilter)
	}
	if len(param.StatusFilter) > 0 {
		db.Where("state in ?", param.StatusFilter)
	}

	// 排序
	if param.SortField != "" && param.SortOrder == "ascend" {
		db.Order(fmt.Sprintf("%s asc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField != "" && param.SortOrder == "descend" {
		db.Order(fmt.Sprintf("%s desc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField == "" {
		db.Order("create_at desc")
	}

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}

func (d *OrderDao) GetOrderListByPlace(param *request.OrderListByPlaceReq) *dingo.ErrorWrap {

	var (
		lst    []orders.OrderListByPlaceModel
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	fields := `our.trade_no,o.id,appid, mchid, openid, out_trade_no, trade_type, trade_state, trade_state_doing, trade_state_desc, 
	state, title, device_sn, shared_mode, fee_mode, o.user_id, user_name, money, money_str, pay_money, pay_money_str, refund_money, 
	settlement_way, settlement_money, settlement_money_str, settlement_state, coupon_type, coupon_money, coupon_money_str, order_from, 
	pay_from, pay_type, place_id, place_name, member_id, member_name, overtime_state, is_delete, is_draw, pay_at, create_at, update_at, 
	refund_at, end_at, delete_at, draw_at, parent_id, product_id, is_tianhai, agent_user_id, ka_user_id, phone, begin_at`
	db := global.Orm.Table("orders o").Select(fields)
	db.Joins("LEFT JOIN orders_user_relevancy our ON o.trade_no=our.trade_no")
	db.Where("our.user_id=?", param.LoginUserId)
	//db.Where("is_draw = ?", 0)
	//db.Where("is_tianhai = ?", 0)

	if param.IsAdmin != helper.TypeNumIsAdminOperator {
		//if param.IsDraw != helper.TypeNumIsDrawOpen {
		//	db.Where("o.is_draw<>? or o.agent_user_id=?", helper.TypeNumIsDrawOpen, param.LoginUserId)
		//} else {
		//	db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, param.LoginUserId)
		//}
		db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, param.LoginUserId)
		db.Where("o.is_tianhai = 0")
	}

	if param.TradeNo != "" { //网点名称
		db.Where("o.trade_no like ?", fmt.Sprint("%", param.TradeNo, "%"))
	}
	if param.OutTradeNo != "" {
		db.Where("out_trade_no like ?", fmt.Sprint("%", param.OutTradeNo, "%"))
	}

	if param.PlaceType == "direct" {
		db.Where("o.user_id=?", param.LoginUserId)
	}
	if param.PlaceType == "children" {
		db.Where("o.user_id<>?", param.LoginUserId)
	}

	//if param.PlaceType == "all" {
	//	// 下级
	//	placeModelLst := NewPlaceDao().GetPlaceByparentId(userId).Unwrap().([]*placemodel.PlaceModel)
	//	placeIdArr := make([]int, 0)
	//	//placeIdArr = append(placeIdArr, param.PlaceId)
	//	for _, placeModel := range placeModelLst {
	//		placeIdArr = append(placeIdArr, placeModel.Id)
	//	}
	//
	//	// 直属
	//	placeDirdectList := NewPlaceDao().GetPlaceByUserId(userId).Unwrap().([]*placemodel.PlaceModel)
	//	for _, lst := range placeDirdectList {
	//		placeIdArr = append(placeIdArr, lst.Id)
	//	}
	//
	//	db.Where("place_id in ?", placeIdArr)
	//} else if param.PlaceType == "direct" {
	//	//db.Where("place_id = ?", param.PlaceId)
	//	placeModelLst := NewPlaceDao().GetPlaceByUserId(userId).Unwrap().([]*placemodel.PlaceModel)
	//	placeIdArr := make([]int, 0)
	//	placeIdArr = append(placeIdArr, param.PlaceId)
	//	for _, placeModel := range placeModelLst {
	//		placeIdArr = append(placeIdArr, placeModel.Id)
	//	}
	//	db.Where("place_id in ?", placeIdArr)
	//} else if param.PlaceType == "children" {
	//	placeModelLst := NewPlaceDao().GetPlaceByparentId(userId).Unwrap().([]*placemodel.PlaceModel)
	//	placeIdArr := make([]int, 0)
	//	for _, placeModel := range placeModelLst {
	//		placeIdArr = append(placeIdArr, placeModel.Id)
	//	}
	//	db.Where("place_id in ?", placeIdArr)
	//}

	if param.DeviceSn != "" { // 查询条件：设备序列号
		db.Where("device_sn like ?", fmt.Sprint("%", param.DeviceSn, "%"))
	}
	if param.State > 0 { // 查询条件：状态
		db.Where("state = ?", param.State)
	} else {
		db.Where("state != 1")
	}

	if param.OrderFrom != "" { // 查询条件：支付方式
		db.Where("order_from = ?", param.OrderFrom)
	}

	if param.SharedMode != "" { // 查询条件：共享模式
		db.Where("shared_mode = ?", param.SharedMode)
	}

	if param.LendBegin != "" && param.LendEnd != "" {
		beginTime := wechatpay.StrTimeToInt(param.LendBegin + " 00:00:00")
		endTime := wechatpay.StrTimeToInt(param.LendEnd + " 23:59:59")
		db.Where("create_at >= ? and create_at<= ?", beginTime, endTime)
	}

	db.Order("our.trade_no desc")

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}

func (d *OrderDao) GetOrderListByAgent(param *request.OrderListByPlaceReq, userId int, isDraw, IsAdmin uint8) *dingo.ErrorWrap {

	var (
		lst    []orders.OrderListByAgentModel
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.Table("orders")

	if IsAdmin != helper.TypeNumIsAdminOperator {
		userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		placesIdArr := NewUserDao().GetPlacesIds(userId, userIdArr).Unwrap().([]int)
		db.Where("place_id in ?", placesIdArr)
	}

	if isDraw != helper.TypeNumIsDrawOpen {
		db.Where("is_draw<>?", 1)
	}

	if param.TradeNo != "" { //网点名称
		db.Where("trade_no like ?", fmt.Sprint("%", param.TradeNo, "%"))
	}
	if param.OutTradeNo != "" {
		db.Where("out_trade_no like ?", fmt.Sprint("%", param.OutTradeNo, "%"))
	}

	if param.DeviceSn != "" { // 查询条件：设备序列号
		db.Where("device_sn like ?", fmt.Sprint("%", param.DeviceSn, "%"))
	}
	if param.State > 0 { // 查询条件：状态
		db.Where("state = ?", param.State)
	}

	if param.OrderFrom != "" { // 查询条件：支付方式
		db.Where("order_from = ?", param.OrderFrom)
	}

	if param.SharedMode != "" { // 查询条件：共享模式
		db.Where("shared_mode = ?", param.SharedMode)
	}

	if param.LendBegin != "" && param.LendEnd != "" {
		beginTime := wechatpay.StrTimeToInt(param.LendBegin + " 00:00:00")
		endTime := wechatpay.StrTimeToInt(param.LendEnd + " 23:59:59")
		db.Where("create_at >= ? and create_at<= ?", beginTime, endTime)
	}

	db.Order("create_at desc")

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}

// GetOrderDetail 获取定单详情
func (d *OrderDao) GetOrderDetailBytTradeNo(tradeNo string) *orders.OrderModel {
	data := &orders.OrderModel{}

	sql := `select * from orders where trade_no = ?`

	global.Orm.Raw(sql, tradeNo).Find(&data)
	return data
}

// GetOrderFirstByPlaceIdAndDeviceSn 查看是否为首单
func (d *OrderDao) GetOrderFirstByPlaceIdAndDeviceSn(placeId int, deviceSn string) *orders.OrderWithPlaceFirst {
	data := &orders.OrderWithPlaceFirst{}

	sql := `SELECT p.is_open_first,a.id,a.place_id,a.device_sn FROM places p 
RIGHT JOIN (SELECT place_id,id,device_sn FROM orders WHERE place_id = ? and device_sn = ? 
ORDER BY id ASC LIMIT 1) a ON p.id = a.place_id `

	global.Orm.Raw(sql, placeId,deviceSn).Find(&data)
	return data
}

// GetOrderDetail 获取定单详情
func (d *OrderDao) GetOrderDetail(orderId int) *dingo.ErrorWrap {
	lst := &resphelper.OrderInfoRes{}
	//sql := " SELECT o.*,d.money_str AS dividendMoneyStr,d.profit_proportion AS dividendProfitProportion," +
	//	" d.user_name AS dividendUserName from orders o LEFT JOIN dividends_log d on o.trade_no = d.trade_no " +
	//	" where o.id = ?"
	sql := `select * from orders where id = ? limit 1`

	db := global.Orm.Raw(sql, orderId).Find(lst)
	return dingo.ErrorIf(db.Error, lst)
}

// GetOrderDetail 获取定单详情
func (d *OrderDao) GetAliPayOrderDetail(orderId int) *dingo.ErrorWrap {
	var (
		lst orders.AliPayOrdersDetail
	)
	//sql := " SELECT o.*,d.money_str AS dividendMoneyStr,d.profit_proportion AS dividendProfitProportion," +
	//	" d.user_name AS dividendUserName from orders o LEFT JOIN dividends_log d on o.trade_no = d.trade_no " +
	//	" where o.id = ?"
	sql := `select * from orders o left join prices p on p.product_id = o.product_id  where o.id = ?`

	db := global.Orm.Raw(sql, orderId).Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

// 获取分成信息
func (d *OrderDao) GetProfitInfo(tradeNo, endTime string) *dingo.ErrorWrap {
	var lst []dividendslog.ProfitInfo
	sql := `select d.id,d.money,d.money_str,d.settlement_money,d.profit_proportion,u.name, u.user_name from dividends_log d 
	left join users u on d.user_id = u.id where d.trade_no=? and end_date=? order by d.id desc`
	db := global.Orm.Debug().Raw(sql, tradeNo, endTime).Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

// SaveOrderStatus 保存订单状态
func (d *OrderDao) SaveOrderStatus(tradeNo string, status int8) {
	global.Rdb.Set(context.Background(), utils.Join(tradeNo, "-status"), status, 0)
}

// UpdateOrder 修改订单信息
func (d *OrderDao) UpdateOrder(m *orders.OrderModel) *dingo.ErrorWrap {
	m.UpdateAt = dingo.Time(time.Now().Unix())
	db := global.Orm.Debug().Table("orders").Where("id = ?", m.Id).Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}

// 修改订单状态
func (d *OrderDao) UpdateOrderState(id, state int) *dingo.ErrorWrap {
	db := global.Orm.Exec("update orders set state = ? where id = ?", state, id)
	return dingo.ErrorIf(db.Error, true)
}

// 修改结算金额
func (d *OrderDao) UpdateOrderSettlementMoney(id int, settlementMoney int64) *dingo.ErrorWrap {
	settlementMoneyStr := decimal.NewFromInt(settlementMoney).Div(decimal.NewFromInt(100)).StringFixed(2)
	db := global.Orm.Exec("update orders set settlement_money = ?,settlement_money_str = ? where id = ?", settlementMoney, settlementMoneyStr, id)
	return dingo.ErrorIf(db.Error, true)
}

// UpdateOrder 修改订单信息
func (d *OrderDao) UpdateOrderByOutTradeNo(m *orders.OrderModel) *dingo.ErrorWrap {
	m.UpdateAt = dingo.Time(time.Now().Unix())
	db := global.Orm.Debug().Table("orders").Where("out_trade_no = ?", m.OutTradeNo).Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}

// 测试用
func (d *OrderDao) UpdateOrderTest(m *orders.OrderModel) *dingo.ErrorWrap {
	db := global.Orm.Table("orders").Where("id = ?", m.Id).Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}

func (d *OrderDao) UpdateOrderStatus(tradeNo string, state int) *dingo.ErrorWrap {
	sql := `update orders set state = ? where trade_no = ?`
	db := global.Orm.Table("orders").Exec(sql, state, tradeNo)
	return dingo.ErrorIf(db.Error, true)
}

func (d *OrderDao) UpdateOrderStatusFromId(id int, state int) *dingo.ErrorWrap {
	sql := `update orders set state = ? where id = ?`
	db := global.Orm.Table("orders").Exec(sql, state, id)
	return dingo.ErrorIf(db.Error, true)
}

// 订单统计
func (d *OrderDao) CountOrder(isAdmin uint8, loginUserId int, isDraw uint8) *dingo.ErrorWrap {
	var data orders.CountOrder
	fields := `SUM(IF(order_from='weixin', 1, 0))count_weixin,SUM(IF(order_from='zhifubao', 1, 0))count_zhifubao,
       SUM(IF(state=2, 1, 0))count_status_serving,SUM(IF(state=3, 1, 0))count_status_revoked,
       SUM(IF(state=5, 1, 0))count_status_returned,SUM(IF(state=7, 1, 0))count_status_waiting`
	db := global.Orm.Table("orders o").Select(fields).
		Joins("LEFT JOIN orders_user_relevancy our on o.trade_no = our.trade_no")
	db.Where("our.user_id=?", loginUserId)

	if isAdmin != helper.TypeNumIsAdminOperator {
		//if isDraw != helper.TypeNumIsDrawOpen {
		//	db.Where("o.is_draw<>? or o.agent_user_id=?", helper.TypeNumIsDrawOpen, loginUserId)
		//} else {
		//	db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, loginUserId)
		//}
		db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, loginUserId)
		db.Where("o.is_tianhai = 0")
	}

	db.Find(&data)
	return dingo.ErrorIf(db.Error, data)
}

// CountWeixin 微信订单统计
func (d *OrderDao) CountWeixin(isAdmin uint8, loginUserId int, isPlace uint8, parentId int) *dingo.ErrorWrap {
	var count int64
	db := global.Orm.Debug().Table("orders")
	if isAdmin == 4 { // 登录是员工
		userIdArr := NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)

		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}
	if isAdmin == 3 && isPlace != 3 { // 登录是代理商
		userIdArr := NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)

		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}

	if isPlace == 3 {
		placeIdArr := NewUserDao().GetPlacesId(loginUserId).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}

	db.Where("order_from = ?", "weixin").Count(&count)

	return dingo.ErrorIf(db.Error, count)
}

// CountZhifubao 支付宝订单统计
func (d *OrderDao) CountZhifubao(isAdmin uint8, loginUserId int, isPlace uint8, parentId int) *dingo.ErrorWrap {
	var count int64
	db := global.Orm.Debug().Table("orders")
	if isAdmin == 4 { // 登录是员工
		userIdArr := NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)

		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}
	if isAdmin == 3 && isPlace != 3 { // 登录是代理商
		userIdArr := NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)

		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}
	if isPlace == 3 {
		placeIdArr := NewUserDao().GetPlacesId(loginUserId).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}

	db.Where("order_from = ?", "zhifubao").Count(&count)
	return dingo.ErrorIf(db.Error, count)
}

// CountStatusServing 服务中统计
func (d *OrderDao) CountStatusServing(isAdmin uint8, loginUserId int, isPlace uint8, parentId int) *dingo.ErrorWrap {
	var count int64
	db := global.Orm.Debug().Table("orders")
	if isAdmin == 4 { // 登录是员工
		userIdArr := NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)

		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}
	if isAdmin == 3 && isPlace != 3 { // 登录是代理商
		userIdArr := NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)

		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}
	if isPlace == 3 {
		placeIdArr := NewUserDao().GetPlacesId(loginUserId).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}
	db.Where("state = ?", 2).Count(&count)
	return dingo.ErrorIf(db.Error, count)
}

// CountStatusReturned 已归还统计
func (d *OrderDao) CountStatusReturned(isAdmin uint8, loginUserId int, isPlace uint8, parentId int) *dingo.ErrorWrap {
	var count int64
	db := global.Orm.Debug().Table("orders")
	if isAdmin == 4 { // 登录是员工
		userIdArr := NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)

		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}
	if isAdmin == 3 && isPlace != 3 { // 登录是代理商
		userIdArr := NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)

		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}
	if isPlace == 3 {
		placeIdArr := NewUserDao().GetPlacesId(loginUserId).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}

	db.Where("state = ?", 5).Count(&count)
	return dingo.ErrorIf(db.Error, count)
}

// 已撤销
func (d *OrderDao) CountStatusRevoked(isAdmin uint8, loginUserId int, isPlace uint8, parentId int) *dingo.ErrorWrap {
	var count int64
	db := global.Orm.Debug().Table("orders")
	if isAdmin == 4 { // 登录是员工

		userIdArr := NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)

		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}
	if isAdmin == 3 && isPlace != 3 { // 登录是代理商
		userIdArr := NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)

		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}
	if isPlace == 3 {
		placeIdArr := NewUserDao().GetPlacesId(loginUserId).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}

	db.Where("state = ?", 3).Count(&count)
	return dingo.ErrorIf(db.Error, count)
}

// CountStatusWaiting 待守约统计
func (d *OrderDao) CountStatusWaiting(isAdmin uint8, loginUserId int, isPlace uint8, parentId int) *dingo.ErrorWrap {
	var count int64
	db := global.Orm.Debug().Table("orders")
	if isAdmin == 4 { // 登录是员工
		userIdArr := NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)

		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}
	if isAdmin == 3 && isPlace != 3 { // 登录是代理商
		userIdArr := NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)

		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}
	if isPlace == 3 {
		placeIdArr := NewUserDao().GetPlacesId(loginUserId).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}

	db.Where("state = ?", 7).Count(&count)
	return dingo.ErrorIf(db.Error, count)
}

// 统计已归还
func (d *OrderDao) CountOrderStatusByAgentId(userId, day, status int, IsAdmin, IsDraw uint8) *dingo.ErrorWrap {
	var count int64

	dateStr := time.Now().AddDate(0, 0, -day).Format("2006-01-02")
	db := global.Orm.Debug().Table("orders o").
		Joins("LEFT JOIN orders_user_relevancy our ON o.trade_no=our.trade_no").
		Where("our.user_id=?", userId).
		//Where("DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) >= date_sub( curdate(), INTERVAL ? DAY )", day).
		Where("state = ?", status)
	if day <= 1 {
		db.Where("DATE_FORMAT(FROM_UNIXTIME(o.end_at),'%Y-%m-%d') = ?", dateStr)
	} else {
		db.Where("DATE_FORMAT(FROM_UNIXTIME(o.end_at),'%Y-%m-%d') >= ?", dateStr)
	}

	if IsAdmin != helper.TypeNumIsAdminOperator {
		//if IsDraw != helper.TypeNumIsDrawOpen {
		//	db.Where("o.is_draw<>? or o.agent_user_id=?", helper.TypeNumIsDrawOpen, userId)
		//} else {
		//	db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, userId)
		//}
		db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, userId)
		db.Where("o.is_tianhai = 0")
	}

	db.Count(&count)
	return dingo.ErrorIf(db.Error, count)
}

//func (d *OrderDao) CountSettMoney() *dingo.ErrorWrap {
//	var totalMoney, count int64
//	m := settlog.New()
//	db := global.Orm.Table("settlement_log").Count(&count)
//	if count <= 0 {
//		totalMoney = 0
//		return dingo.ErrorIf(db.Error, totalMoney)
//	}
//	sql := `select
//					SUM(sett_money) as total_money
//				from
//					settlement_log `
//	db2 := global.Orm.Model(m).
//		Raw(sql).
//		Pluck("SUM(sett_money) as total_money", &totalMoney)
//
//	return dingo.ErrorIf(db2.Error, totalMoney)
//}

func (d *OrderDao) InsertDividends(tx *gorm.DB, m *dividendslog.DividendsLog) *dingo.ErrorWrap {
	db := tx.Table("dividends_log").Create(m)
	return dingo.ErrorIf(db.Error, true)
}

//
//func (d *OrderDao) OrderTotalByPlace(param *request.OrderTotalReq) *dingo.ErrorWrap {
//	var (
//		lst   []orders.OrderTotalModel
//		count int64
//		//limit  int = param.PageSize
//		//offset int = param.PageSize * (param.PageNo - 1)
//	)
//
//	//select a.place_id,p.place_name,a.orderTotal,p.device_count,a.turnover
//	//	,a.orderTotal/(p.device_count*30) usageRate,(a.turnover/a.orderTotal)/100 arpa
//	//	from  (SELECT o.place_id,count(1) orderTotal,SUM(o.settlement_money) turnover FROM orders o WHERE  o.create_at >= '1606752000' and o.create_at <= '1609430399'  GROUP BY o.place_id) a  left JOIN places p on a.place_id = p.id
//	//	ORDER BY usageRate desc
//	//	-- ORDER BY arpa desc
//
//	//sql := " SELECT o.place_id,count(1) orderTotal,SUM(o.settlement_money) turnover FROM orders o WHERE " +
//	//	   " o.create_at >= ? and o.create_at <= ? " +
//	//	   " GROUP BY o.place_id"
//
//
//	// 1、商户订单总数/(商户设备总数*天数) ---使用率 备注：一条订单相当于一次设备的使用
//	// (营业额/订单总数)/100  --- 客单价
//
//
//	sql := `SELECT a.place_id,p.place_name,a.orderTotal,p.device_count,a.turnover,
//a.orderTotal/(p.device_count*(SELECT DATEDIFF(DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d'),
//(a.turnover/a.orderTotal)/100 arpa from
//(SELECT o.place_id,count(1) orderTotal,SUM(o.settlement_money) turnover FROM orders o WHERE  o.create_at >= ? and o.create_at <= ?  GROUP BY o.place_id) a
//left JOIN places p on a.place_id = p.id  ORDER BY usageRate desc`
//
//	searchTime := strings.Split(param.SearchTime, ",")
//
//	db := global.Orm.Raw(sql, searchTime[1], searchTime[0], searchTime[0], searchTime[1]).Find(&lst)
//
//	//db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)
//
//	return dingo.ErrorIf(db.Error, lst, count)
//}

func (d *OrderDao) GetOrderListByPlaceId(limit, offset, placeId int) *dingo.ErrorWrap {
	var lst []orders.OrderModel

	db := global.Orm.Table("orders").Where("place_id = ?", placeId)
	db.Order("create_at desc")
	db.Limit(limit).Offset(offset).Find(&lst)

	return dingo.ErrorIf(db.Error, lst)
}

// 计算近10天的收益
func (d *OrderDao) GetDividendsListByUserId(userId int) *dingo.ErrorWrap {
	// 计算最近
	var lst []dividendslog.PlaceProfitInfoByDay
	sql := `SELECT SUM(money)/100 as total,DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') AS day,
id,user_name FROM dividends_log WHERE user_id = ? 
GROUP BY DATE_FORMAT(FROM_UNIXTIME(create_at), '%Y-%m-%d') ORDER BY create_at DESC LIMIT 10`
	db := global.Orm.Raw(sql, userId).Find(&lst)

	return dingo.ErrorIf(db.Error, lst)
}

// 获取收益列表
func (d *OrderDao) GetIncomeList(param *request.IncomeListReq) *dingo.ErrorWrap {
	//placeInfo := NewUserDao().GetUserInfoByUserId(param.UserId).Unwrap().(users.UserInfoPlaceId)
	//var (
	//	lst    []incomes.IncomeModel
	//	count  int64
	//	limit  int = param.PageSize
	//	offset int = param.PageSize * (param.PageNo - 1)
	//)
	//
	//db := global.Orm.Debug().Table("orders_statistics").Where("place_id = ?", placeInfo.PlaceId)
	//
	//db.Order("create_at desc")
	//
	//db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)
	//
	//return dingo.ErrorIf(db.Error, lst, count)

	var (
		lst    []incomes.IncomeModel
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	fields := `create_at ,SUM(money) Income`
	db := global.Orm.Debug().Table("dividends_log").Select(fields).Where("user_id = ?", param.UserId)
	db.Group("DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' )").Order("create_at desc")

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}

// 获取收益明细表
func (d *OrderDao) GetIncomeDetailList(param *request.IncomeListReq) *dingo.ErrorWrap {

	var (
		lst    []dividendslog.DividendsLog
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.Table("dividends_log")
	if param.UserId > 0 {
		db.Where("user_id = ?", param.UserId)
	}
	//db.Order("create_at desc")
	//db.Order("id asc")
	db.Order("id desc")

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}

// 导出近3天的重复订单
func (d *OrderDao) ExportRepeatOrder(param *request.OrderListReq) *dingo.ErrorWrap {
	var (
		lst []orders.OrderModel
	)
	//	sql := `SELECT * FROM orders WHERE member_id IN (SELECT member_id FROM orders WHERE
	// DATE_FORMAT(FROM_UNIXTIME( create_at ), '%Y-%m-%d') >= date_sub(curdate(), INTERVAL 3 DAY)
	//	and DATE_FORMAT(FROM_UNIXTIME(create_at), '%Y-%m-%d') <= date_format(curdate(), '%Y-%m-%d')
	//GROUP BY device_sn,member_id HAVING count(member_id)>2 ORDER BY create_at desc)`

	//sql := `SELECT * FROM orders WHERE member_id IN (SELECT member_id FROM orders WHERE
	// DATE_FORMAT(FROM_UNIXTIME( create_at ), '%Y-%m-%d') >= date_sub(curdate(), INTERVAL 2 DAY)
	//	and DATE_FORMAT(FROM_UNIXTIME(create_at), '%Y-%m-%d') <= date_format(curdate(), '%Y-%m-%d')
	//GROUP BY device_sn,member_id HAVING count(member_id)>2 ORDER BY create_at desc) ORDER BY create_at desc`

	sql := `SELECT
 * 
FROM
 orders 
WHERE
 member_id IN (
 SELECT
  member_id 
 FROM
  orders 
 WHERE
  DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) >= date_sub( curdate(), INTERVAL 1 DAY ) 
  AND DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) <= date_format( curdate(), '%Y-%m-%d' ) 
 GROUP BY
  device_sn,
  member_id 
 HAVING
  count( member_id )> 2 
 ORDER BY
  create_at DESC 
 ) 
 AND
 DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) >= date_sub( curdate(), INTERVAL 1 DAY ) 
  AND DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) <= date_format( curdate(), '%Y-%m-%d' ) 
ORDER BY
 create_at DESC`

	db := global.Orm.Raw(sql).Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

//func (d *OrderDao) UpdateOrderByTradeNoAndOpenid(tradeNo, openid, tradeStateDesc, tradeStateDoing, state string) *dingo.ErrorWrap {
//	sql := "update orders set trade_state_desc = ?,trade_state_doing = ?,trade_state = ?  where trade_no = ? and openid = ?"
//	db := global.Orm.Debug().Exec(sql, tradeStateDesc, tradeStateDoing, state, tradeNo, openid)
//	return dingo.ErrorIf(db.Error, true)
//}

// UpdateOrder 修改订单信息
func (d *OrderDao) UpdateOrderByTradeNoAndOpenid(m *orders.OrderModel) *dingo.ErrorWrap {
	m.UpdateAt = dingo.Time(time.Now().Unix())
	db := global.Orm.Debug().Table("orders").
		Where("trade_no = ?", m.TradeNo).
		Where("openid = ?", m.Openid).
		Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}

func (d *OrderDao) UpdateOrderByTradeNo(m *orders.OrderModel) *dingo.ErrorWrap {
	m.UpdateAt = dingo.Time(time.Now().Unix())
	db := global.Orm.Debug().Table("orders").
		Where("trade_no = ?", m.TradeNo).
		Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}

func (d *OrderDao) UpdateOrderIsDraw(m *orders.OrderModel) *dingo.ErrorWrap {
	updateBak := map[string]interface{}{
		"is_draw":    0,
		"is_tianhai": 0,
	}
	db := global.Orm.Model(m).Table("orders").Where("trade_no = ?", m.TradeNo).Updates(&updateBak)
	//db := global.Orm.Debug().Table("orders").
	//	Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}

// 计算商户的收益总额 - 公众号
func (d *OrderDao) GetUserIncome(userId int) *dingo.ErrorWrap {
	var total int64
	sql := `SELECT IFNULL(SUM(money), 0) FROM dividends_log WHERE user_id = ? and is_tianhai = 0`
	db := global.Orm.Raw(sql, userId).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 计算网点的收益总额 - 公众号
func (d *OrderDao) GetPlaceIncome(placeIds []int, userId int) *dingo.ErrorWrap {
	var lst []orders.PlaceIncome

	db := global.Orm.Debug().Table("dividends_log").Select("SUM(money) as money,place_id")
	db.Where("place_id IN (?)", placeIds).Where("user_id=?", userId).Group("place_id").Find(&lst)

	return dingo.ErrorIf(db.Error, lst)
}

// 计算商户某一时间内的收益 placeId 商户ID day 进场时间
func (d *OrderDao) GetUserIncomeBeginTime(placeId int, day int64) *dingo.ErrorWrap {
	var total int64
	sql := `SELECT IFNULL(SUM(money), 0) FROM dividends_log WHERE place_id = ? and is_tianhai = 0 and
 DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) >= DATE_FORMAT( FROM_UNIXTIME( ? ), '%Y-%m-%d' ) 
  AND DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) <= date_sub( curdate(), INTERVAL 1 DAY ) `
	db := global.Orm.Debug().Raw(sql, placeId, day).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

//查询退款订单总额
func (d *OrderDao) GetRefundsTotal(outTradeNo string) *dingo.ErrorWrap {
	var total int64
	sqlStr := "SELECT IFNULL(SUM(settlement_refund_fee), 0) FROM refunds WHERE trade_no = ? GROUP BY trade_no"
	db := global.Orm.Debug().Raw(sqlStr, outTradeNo).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

//查询退款订单总额
func (d *OrderDao) GetRefundsByTransactionIdTotal(outTradeNo string) *dingo.ErrorWrap {
	var total int64
	sqlStr := "SELECT IFNULL(SUM(refund_fee), 0) FROM refunds WHERE out_trade_no = ? "
	db := global.Orm.Debug().Raw(sqlStr, outTradeNo).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

func (d *OrderDao) GetRefundsByTradeNoTotal(tradeNo string) *dingo.ErrorWrap {
	var total int64
	sqlStr := "SELECT IFNULL(SUM(refund_fee), 0) FROM refunds WHERE trade_no = ? "
	db := global.Orm.Debug().Raw(sqlStr, tradeNo).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 查询订单是否分红
func (d *OrderDao) SelectDividendsLogByTradeNo(tradeNo string) *dingo.ErrorWrap {
	var count int64
	sql := "select count(1) from dividends_log where trade_no = ?"
	db := global.Orm.Debug().Raw(sql, tradeNo).Count(&count)
	return dingo.ErrorIf(db.Error, count)
}

func (d *OrderDao) DeleteDividendsLog(tradeNo string) *dingo.ErrorWrap {
	db := global.Orm.Debug().Exec("delete from dividends_log where trade_no = ?", tradeNo)
	return dingo.ErrorIf(db.Error, true)
}

func (d *OrderDao) BatchDeleteDividendsLog(tradeNo []string) *dingo.ErrorWrap {
	db := global.Orm.Debug().Exec("delete from dividends_log where trade_no in(?)", tradeNo)
	return dingo.ErrorIf(db.Error, true)
}

func (d *OrderDao) GetDeviceInfo(deviceSn string) *dingo.ErrorWrap {
	m := &devices.DeviceType{}
	db := global.Orm.Debug().Table("devices").Where("device_sn = ?", deviceSn).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

func (d *OrderDao) OrderInfoByTradeNo(tradeNo string) *dingo.ErrorWrap {
	m := orders.New()
	//sql := "select * from orders where trade_no = ? and create_time = ?"
	//db := global.Orm.Raw(sql, tradeNo, createTime).Find(&m)
	db := global.Orm.Table("orders").
		Where("trade_no = ?", tradeNo).
		Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

func (d *OrderDao) GetOrderExportList(param *request.OrderListReq) *dingo.ErrorWrap {

	var (
		lst    []*orders.OrderExportModel
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.Debug().Table("orders")
	if param.LoginUserId != 2 {
		db.Select("trade_no,out_trade_no,state,member_name,order_from,place_name,device_sn,pay_money," +
			"place_id,phone,settlement_money,trade_state_desc,create_at,end_at,user_id,user_name,is_draw,coupon_type,coupon_money").
			Where("is_tianhai = 0")
	} else {
		db.Select("trade_no,out_trade_no,state,member_name,order_from,place_name,device_sn,pay_money," +
			"place_id,phone,settlement_money,trade_state_desc,create_at,end_at,user_id,user_name,is_draw,coupon_type,coupon_money,is_tianhai")
	}

	userInfo := NewUserDao().GetUserInfoById(param.ParentId).Unwrap().(*users.UserModel)

	// 代理商不显示奖励
	if param.IsAdmin == helper.TypeNumIsAdminAgent && param.IsPlace != helper.TypeNumIsPlaceKa {
		if param.IsDraw != helper.TypeNumIsDrawOpen {
			db.Where("is_draw<>?", 1)
		}
	}

	//log.Println("当前账号例如：",param.IsAdmin,userInfo.IsAdmin,param.ParentId )
	// 当前员工不属于运营商
	if param.IsAdmin == 4 && userInfo.IsAdmin != 2 {
		// 当前账号登录维护员工，可以查询该员工所在运营商或是代理商的所有订单，方便管理
		placeModelLst := NewPlaceDao().GetPlaceByparentId(param.ParentId).Unwrap().([]*placemodel.PlaceModel)
		// 获取维护者所维护的商户ID
		placeIdArr := make([]int, 0)
		for _, placeModel := range placeModelLst {
			placeIdArr = append(placeIdArr, placeModel.Id)
		}
		db.Where("place_id in ?", placeIdArr)
	}

	// 当前账号登录是代理商或是合伙人
	if (param.IsAdmin == helper.TypeNumIsAdminAgent || param.IsAdmin == helper.TypeNumIsAdminPartner) && param.IsPlace != helper.TypeNumIsPlaceKa {

		// 查询代理商所有下级
		userIdArr := NewUserDao().QueryChildUserIds(param.LoginUserId).Unwrap().([]int)
		userIdArr = append(userIdArr, param.LoginUserId)
		placeModelLst := NewPlaceDao().GetPlaceByParentIds(userIdArr).Unwrap().([]*placemodel.PlaceModel)
		placeIdArr := make([]int, 0)
		for _, placeModel := range placeModelLst {
			placeIdArr = append(placeIdArr, placeModel.Id)
		}
		db.Where("place_id in ?", placeIdArr)
	}

	// 当前账号登录是分公司帐号处理
	if param.IsPlace == helper.TypeNumIsPlaceKa {
		placesIdArr := NewUserDao().GetPlacesId(param.LoginUserId).Unwrap().([]int)
		userIdArr := NewUserDao().QueryChildUserIds(param.LoginUserId).Unwrap().([]int)
		db.Where("(place_id in (?) or user_id in (?))", placesIdArr, userIdArr)
	}
	if param.AgentUserId > 0 {
		userIdArr := NewUserDao().QueryChildUserIds(param.AgentUserId).Unwrap().([]int)
		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		db.Where("place_id in (?)", placeIdArr)
	}

	if param.TradeNo != "" { //网点名称
		db.Where("trade_no like ?", fmt.Sprint("%", param.TradeNo, "%"))
	}
	if param.OutTradeNo != "" {
		db.Where("out_trade_no like ?", fmt.Sprint("%", param.OutTradeNo, "%"))
	}
	if param.PlaceId > 0 {
		db.Where("is_draw = ?", 0)
		db.Where("place_id = ?", param.PlaceId)
	}

	//db.Where("DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d')<='2021-06-30'  and DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d')>='2021-06-01' and  state = 5")

	if param.Phone != "" {
		db.Where("phone like ?", fmt.Sprint("%", param.Phone, "%"))
	}
	if param.PlaceName != "" { // 查询条件：网点名称
		db.Where("place_name like ? ", fmt.Sprint("%", param.PlaceName, "%"))
	}
	if param.DeviceSn != "" { // 查询条件：设备序列号
		db.Where("device_sn like ?", fmt.Sprint("%", param.DeviceSn, "%"))
	}
	if param.State > 0 { // 查询条件：状态
		db.Where("state = ?", param.State)
	}
	if param.SettlementState > 0 { // 查询条件：异常状态
		db.Where("settlement_state = ?", param.SettlementState)
	}
	if param.OrderFrom != "" { // 查询条件：支付方式
		db.Where("order_from = ?", param.OrderFrom)
	}
	if param.PayFrom != "" { // 查询条件：支付方式
		db.Where("pay_from = ?", param.PayFrom)
	}
	if param.SharedMode != "" { // 查询条件：共享模式
		db.Where("shared_mode = ?", param.SharedMode)
	}
	if param.TradeType != "" { // 查询条件：收费模式
		db.Where("trade_type = ?", param.TradeType)
	}
	if param.UserId > 0 { // 选择代理商用户ID
		if param.IsNext > 0 { // 是否查询下级
			// 获取该用户下的所有代理商的用户ID
			//pidArr := []int{param.UserId}
			//userIdArr := NewUserDao().GetUserIdByPid(param.UserId).Unwrap().([]int)
			//if len(userIdArr) > 0 {
			//	 NewUserDao().GetUserIdByPid(userIdArr).Unwrap().([]int)
			//}
			//
			//append(userIdArr, )
			// 获取该代理商下的所有网点ID
			//db.Where("user_id in (?)", userIdArr)
		} else {
			// 获取该代理商下的所有网点ID
			db.Where("user_id = ?", param.UserId)

		}
	}

	if param.MemberId != "" {
		db.Where("member_id = ?", param.MemberId)
	}

	// 时间查询
	if param.BeginTime != "" {
		beginTime := strings.Split(param.BeginTime, ",")
		db.Where("DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') >=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') and "+
			"DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d')<=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", beginTime[0], beginTime[1])
	}
	if param.EndTime != "" {
		endTime := strings.Split(param.EndTime, ",")
		db.Where("DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') >=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') and "+
			"DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d')<=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime[0], endTime[1])
	}

	// 过滤
	if len(param.PayFromFilter) > 0 {
		db.Where("pay_from in ?", param.PayFromFilter)
	}
	if len(param.OrderFromFilter) > 0 {
		db.Where("order_from in ?", param.OrderFromFilter)
	}
	if len(param.StatusFilter) > 0 {
		db.Where("state in ?", param.StatusFilter)
	}

	// 排序
	if param.SortField != "" && param.SortOrder == "ascend" {
		db.Order(fmt.Sprintf("%s asc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField != "" && param.SortOrder == "descend" {
		db.Order(fmt.Sprintf("%s desc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField == "" {
		db.Order("create_at desc")
	}

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}

// 网点导出计算余额
func (d *OrderDao) GetUserIncomeIn(userIds []int) *dingo.ErrorWrap {
	//var total []int64
	var model []orders.GetUserIncomeModel
	sql := `SELECT SUM( dl.money ) AS money,cash_total,dl.user_id FROM dividends_log dl LEFT JOIN (select IFNULL(SUM(transfer_money),0) as cash_total ,user_id from cash_log WHERE state = 2 GROUP BY user_id  ) cl on cl.user_id = dl.user_id WHERE 1=1 and dl.user_id in (?) GROUP BY dl.user_id `
	db := global.Orm.Raw(sql, userIds).Find(&model)
	return dingo.ErrorIf(db.Error, model)
}

//func (d *OrderDao) GetUserIncomeIn(placeIds []int) *dingo.ErrorWrap {
//	//var total []int64
//	var model []orders.GetUserIncomeModel
//	sql := `SELECT IFNULL(SUM(d.money), 0)  as money  ,d.user_id FROM dividends_log d WHERE d.place_id in (?) and d.is_tianhai = 0 GROUP BY d.user_id`
//	db := global.Orm.Raw(sql, placeIds).Find(&model)
//	return dingo.ErrorIf(db.Error, model)
//}

//修改为抽单订单
func (d *OrderDao) UpdateOrderForIsDraw(m *orders.OrderModel) *dingo.ErrorWrap {
	db := global.Orm.Debug().Model(m).Select("is_draw", "agent_user_id").Table("orders").Where("trade_no = ?", m.TradeNo).Updates(&m)
	//db := global.Orm.Debug().Table("orders").
	//	Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}

func (d *OrderDao) AliPayOrdersList(param *request.OrderListReq) *dingo.ErrorWrap {
	var (
		lst    []*orders.AliPayOrdersModel
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.Debug().Table("orders")

	if param.MemberId != "" {
		db.Where("member_id = ?", param.MemberId)
	}

	db.Order("create_at desc")

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}

//查询投诉订单是否入库过
func (d *OrderDao) GetComplaintsIsCreate(complaintId string) *dingo.ErrorWrap {
	var totalCount int64
	db := global.Orm.Table("complaints_log").Select("count(1) totalCount").
		Where("complaint_id = ?", complaintId).
		Find(&totalCount)
	return dingo.ErrorIf(db.Error, totalCount)
}

//修改投诉订单日志
func (d *OrderDao) UpdateComplaintsLog(m *complaintslog.TransitionComplaintsLog) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("complaints_log").Where("complaint_id = ?", m.ComplaintId).Model(m).Updates(&m)
	return dingo.ErrorIf(db.Error, true)

}

//投诉订单日志入库
func (d *OrderDao) CreateComplaintsLog(m *complaintslog.TransitionComplaintsLog) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("complaints_log").Create(&m)
	return dingo.ErrorIf(db.Error, true)
}
